package br.edu.ufcg.fpc;

import br.edu.ufcg.fpc.locks.BakeryLock;
import br.edu.ufcg.fpc.locks.BakeryLockAO;
import br.edu.ufcg.fpc.locks.BakeryLockIF;

/**
 * Protege a regiao critica utilizando a trava BakeryLock.
 */
public class BakeryLockCR extends CriticalRegion {

	static BakeryLockIF LOCK;

	static int CURRENT_MAX_ID = 0;
	
	private int threadId;
	
	public BakeryLockCR(Boolean atomic) {
		if (LOCK == null) {
			if (atomic) {
				LOCK = new BakeryLockAO(MutualExclusion.nThreads);
			} else {
				LOCK = new BakeryLock(MutualExclusion.nThreads);
			}
		}
		threadId = CURRENT_MAX_ID++;
	}

	@Override
	protected void executeCriticalRegion() {
		long before = System.nanoTime();
		LOCK.lock(threadId);
		addTime(System.nanoTime() - before);
		increment();
		LOCK.unlock(threadId);
	}
	
}
